package com.springapp.mvc.controllers;

import com.springapp.mvc.dto.PostCommentBody;
import com.springapp.mvc.dto.PostResult;
import com.springapp.mvc.entity.CommentForPost;
import com.springapp.mvc.services.PostingService;
import com.springapp.mvc.util.ExecUtil;
import com.springapp.mvc.util.PostAction;
import com.springapp.mvc.util.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * Created by dbychkov on 13.01.2015.
 */
@Controller
@RequestMapping("/comments")
public class CommentController {

    private static final String NOT_LOOGED_IN = "You are not logged in";

    @Autowired
    private PostingService postingService;

    @RequestMapping(value = "/fetch/{post_id}",
                    method = RequestMethod.GET)
    public @ResponseBody List<CommentForPost> getComments(@PathVariable("post_id") long postId) {
        return postingService.getCommentsForPost(postId);
    }

    @RequestMapping(value = "/post",
                    method = RequestMethod.POST,
                    produces = MediaType.APPLICATION_JSON_VALUE,
                    consumes = MediaType.APPLICATION_JSON_VALUE)
    public @ResponseBody PostResult postComment(@RequestBody PostCommentBody postBody) {
        final Long currentUserId = SecurityUtils.getCurrentUserId();
        final Long postId = postBody.getPostId();
        final String message = postBody.getMessage();

        return ExecUtil.exec(new PostAction() {
            @Override
            public void perform() {
                if (currentUserId == null) {
                    throw new RuntimeException(NOT_LOOGED_IN);
                }
                postingService.createComment(postId, currentUserId, message);
            }
        });
    }
}
